<template>
  <div class="chat-container" :class="`theme-${currentTheme}`">
    <particle-background :theme="currentTheme" :particle-count="40" />
    
    <div class="chat-header">
      <router-link to="/" class="back-btn">
        <span>&larr;</span> 返回
      </router-link>
      <h1>AI 编程大师</h1>
      <button class="theme-toggle" @click="showThemeSelector = !showThemeSelector">
        <span class="theme-icon">🎨</span>
      </button>
      <div class="session-id">会话ID: {{ chatId }}</div>
    </div>
    
    <div class="theme-selector" v-if="showThemeSelector">
      <theme-switcher 
        :themes="availableThemes" 
        :active-theme="currentTheme" 
        @change-theme="changeTheme"
      />
    </div>
    
    <div class="messages-container" ref="messagesContainer">
      <div v-if="messages.length === 0" class="welcome-message">
        <h3>欢迎使用AI编程大师</h3>
        <p>您的专属代码顾问已准备就绪，可以解答您关于编程、技术方面的问题。</p>
        <div class="suggestion-list">
          <div class="suggestion-title">您可以尝试询问：</div>
          <div class="suggestion-item" @click="useExample('如何用Python实现二分查找算法？')">如何用Python实现二分查找算法？</div>
          <div class="suggestion-item" @click="useExample('React中如何管理复杂的状态？')">React中如何管理复杂的状态？</div>
          <div class="suggestion-item" @click="useExample('请编写一个简单的网页爬虫代码')">请编写一个简单的网页爬虫代码</div>
        </div>
      </div>
      
      <chat-message
        v-for="(message, index) in messages"
        :key="index"
        :content="message.content"
        :is-user="message.isUser"
        :timestamp="message.timestamp || Date.now()"
        avatar-type="codemaster"
      />
    </div>
    
    <chat-input 
      :is-loading="loading" 
      @send="sendMessage"
    />
  </div>
</template>

<script>
import { v4 as uuidv4 } from 'uuid'
import ChatMessage from '../components/ChatMessage.vue'
import ChatInput from '../components/ChatInput.vue'
import ParticleBackground from '../components/ParticleBackground.vue'
import ThemeSwitcher from '../components/ThemeSwitcher.vue'
import { createLoveMasterChat } from '../api'

export default {
  name: 'CodeMasterView',
  components: {
    ChatMessage,
    ChatInput,
    ParticleBackground,
    ThemeSwitcher
  },
  data() {
    return {
      chatId: '',
      messages: [],
      loading: false,
      eventSource: null,
      currentTheme: 'blue',
      showThemeSelector: false,
      requestInProgress: false,
      maxRetryAttempts: 3,
      retryAttempts: 0,
      backendDown: false,
      availableThemes: [
        {
          id: 'blue',
          name: '深蓝代码',
          colors: {
            primary: '#2196f3',
            secondary: '#1565c0'
          }
        },
        {
          id: 'dark',
          name: '暗黑模式',
          colors: {
            primary: '#424242',
            secondary: '#212121'
          }
        },
        {
          id: 'green',
          name: '翠绿终端',
          colors: {
            primary: '#4caf50',
            secondary: '#2e7d32'
          }
        },
        {
          id: 'purple',
          name: '紫色科技',
          colors: {
            primary: '#9c27b0',
            secondary: '#6a1b9a'
          }
        }
      ],
      reconnectionDelay: 2000,
      keepConnection: true,
      lastMessage: '',
    }
  },
  created() {
    // 尝试从localStorage加载主题设置
    const savedTheme = localStorage.getItem('codeMasterTheme');
    if (savedTheme && this.availableThemes.some(theme => theme.id === savedTheme)) {
      this.currentTheme = savedTheme;
    }
    
    // 生成一个唯一的聊天室ID
    this.chatId = uuidv4()
    
    // 添加一条欢迎消息
    this.messages.push({
      content: '你好！我是AI编程大师，有什么关于编程技术方面的问题可以问我。',
      isUser: false
    })

    // 设置页面标题
    document.title = 'AI编程大师 - 专业的编程辅助服务';
  },
  head: {
    title: 'AI编程大师 - 专业的编程辅助服务',
    meta: [
      { name: 'description', content: 'AI编程大师为您提供专业的编程技术支持，解答开发问题，生成代码示例，帮助您解决技术难题。' },
      { name: 'keywords', content: 'AI编程大师,编程助手,代码生成,技术顾问,AI开发支持' }
    ]
  },
  methods: {
    sendMessage(message) {
      console.log('发送消息:', message)
      
      // 如果已经有一个请求正在进行中，则忽略新的请求
      if (this.requestInProgress) {
        console.log('请求正在处理中，忽略新请求')
        return
      }
      
      // 设置请求处理中状态
      this.requestInProgress = true
      
      // 重置重试状态和后端状态标志
      this.retryAttempts = 0;
      this.backendDown = false;
      
      // 添加用户消息到聊天记录
      this.messages.push({
        content: message,
        isUser: true,
        timestamp: Date.now()
      })
      
      // 滚动到底部
      this.$nextTick(() => {
        this.scrollToBottom()
      })
      
      this.loading = true
      
      // 关闭之前的连接（如果有）
      if (this.eventSource) {
        this.eventSource.close()
      }
      
      // 创建新的SSE连接
      this.eventSource = createLoveMasterChat(message, this.chatId)
      
      // 创建一个新的AI消息占位
      const aiMessageIndex = this.messages.length
      this.messages.push({
        content: '',
        isUser: false,
        timestamp: Date.now()
      })
      
      // 处理返回的消息流
      this.eventSource.onmessage = (event) => {
        try {
          const response = event.data
          if (response) {
            // 更新AI消息内容
            this.messages[aiMessageIndex].content += response
            
            // 检查用户是否在底部，仅当用户在底部时自动滚动
            this.$nextTick(() => {
              const container = this.$refs.messagesContainer
              if (container) {
                // 检查是否在底部或接近底部
                const isAtBottom = container.scrollHeight - container.scrollTop - container.clientHeight < 100
                if (isAtBottom) {
                  this.scrollToBottom()
                }
              }
            })
          }
        } catch (error) {
          console.error('处理消息时出错:', error)
        }
      }
      
      // 错误处理
      this.eventSource.onerror = (error) => {
        console.error('SSE连接错误:', error)
        
        this.retryAttempts++;
        
        // 如果重试次数超过最大尝试次数，判断为后端服务不可用
        if (this.retryAttempts >= this.maxRetryAttempts) {
          console.log(`重试次数达到上限 (${this.maxRetryAttempts})，后端服务可能不可用`)
          this.backendDown = true;
          
          // 添加系统消息提示用户
          this.messages.push({
            content: "已和后台服务断开SSE连接，如您有问题可再次提问",
            isUser: false,
            isSystemMessage: true,
            timestamp: Date.now()
          });
          
          // 关闭连接
          if (this.eventSource) {
            this.eventSource.close();
          }
          
          this.loading = false;
          this.requestInProgress = false;
          
          // 滚动到底部显示错误消息
          this.$nextTick(() => {
            this.scrollToBottom();
          });
        } else {
          console.log(`连接中断，尝试自动重连... (尝试 ${this.retryAttempts}/${this.maxRetryAttempts})`)
          if (this.eventSource) {
            this.eventSource.close();
          }
          this.loading = false;
          // 确保此处不阻止用户发送新消息
          this.requestInProgress = false;
        }
      }
      
      // 连接关闭时清理状态
      this.eventSource.onclose = () => {
        this.loading = false
        // 重置请求状态
        this.requestInProgress = false
      }
    },
    scrollToBottom() {
      const container = this.$refs.messagesContainer
      if (container) {
        container.scrollTop = container.scrollHeight
      }
    },
    useExample(example) {
      this.sendMessage(example)
    },
    changeTheme(theme) {
      this.currentTheme = theme;
      localStorage.setItem('codeMasterTheme', theme);
      this.showThemeSelector = false;
    }
  },
  beforeUnmount() {
    // 组件销毁前关闭SSE连接
    if (this.eventSource) {
      this.eventSource.close()
    }
  }
}
</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: linear-gradient(135deg, #f9f0ff 0%, #f5f0ff 50%, #f0e6ff 100%);
  position: relative;
  width: 100%;
  overflow: hidden;
}

.chat-container::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-image: 
    radial-gradient(circle at 20% 30%, rgba(156, 39, 176, 0.03) 0%, transparent 50%),
    radial-gradient(circle at 70% 60%, rgba(103, 58, 183, 0.03) 0%, transparent 50%);
  z-index: 0;
}

/* 紫色主题 - 默认 */
.theme-purple {
  --primary-color: #9c27b0;
  --secondary-color: #673ab7;
  --gradient: linear-gradient(to right, #9c27b0, #673ab7);
  --bg-gradient: linear-gradient(135deg, #f9f0ff 0%, #f5f0ff 50%, #f0e6ff 100%);
}

/* 粉色主题 */
.theme-pink {
  --primary-color: #ec407a;
  --secondary-color: #e91e63;
  --gradient: linear-gradient(to right, #ec407a, #e91e63);
  --bg-gradient: linear-gradient(135deg, #fff0f5 0%, #fff0f8 50%, #fff0f2 100%);
}

/* 深紫主题 */
.theme-dark-purple {
  --primary-color: #9575cd;
  --secondary-color: #512da8;
  --gradient: linear-gradient(to right, #9575cd, #512da8);
  --bg-gradient: linear-gradient(135deg, #ede7f6 0%, #e8eaf6 50%, #d1c4e9 100%);
}

/* 青色主题 */
.theme-teal {
  --primary-color: #00897b;
  --secondary-color: #26a69a;
  --gradient: linear-gradient(to right, #00897b, #26a69a);
  --bg-gradient: linear-gradient(135deg, #e0f2f1 0%, #e0f7fa 50%, #b2dfdb 100%);
}

.theme-purple .chat-container,
.theme-pink .chat-container,
.theme-dark-purple .chat-container,
.theme-teal .chat-container {
  background: var(--bg-gradient);
}

.chat-header {
  padding: 14px 20px;
  background: var(--gradient, linear-gradient(to right, #9c27b0, #673ab7));
  color: white;
  display: flex;
  align-items: center;
  position: relative;
  box-shadow: 0 2px 15px rgba(156, 39, 176, 0.3);
  z-index: 10;
  animation: headerGlow 5s infinite alternate;
}

.theme-toggle {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  margin-right: 12px;
  color: white;
  transition: all 0.3s;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.theme-toggle:hover {
  background: rgba(255, 255, 255, 0.3);
  transform: rotate(30deg);
}

.theme-icon {
  font-size: 16px;
}

.theme-selector {
  position: absolute;
  top: 60px;
  right: 20px;
  z-index: 100;
  background: rgba(255, 255, 255, 0.95);
  padding: 10px;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
  animation: fadeInDown 0.3s ease-out;
  backdrop-filter: blur(10px);
  border: 1px solid rgba(0, 0, 0, 0.05);
}

@keyframes fadeInDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes headerGlow {
  0% {
    box-shadow: 0 2px 15px rgba(156, 39, 176, 0.2);
  }
  100% {
    box-shadow: 0 2px 20px rgba(156, 39, 176, 0.4);
  }
}

.back-btn {
  color: white;
  text-decoration: none;
  display: flex;
  align-items: center;
  margin-right: 16px;
  padding: 6px;
  border-radius: 6px;
  transition: all 0.3s;
}

.back-btn:hover {
  background-color: rgba(255, 255, 255, 0.15);
  color: white;
  transform: translateX(-2px);
}

.back-btn span {
  margin-right: 4px;
  font-size: 18px;
}

.chat-header h1 {
  flex: 1;
  text-align: center;
  font-size: var(--font-lg);
  margin: 0;
  font-weight: 500;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.2);
}

.session-id {
  font-size: var(--font-xs);
  opacity: 0.85;
  padding: 3px 8px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  backdrop-filter: blur(5px);
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 24px;
  display: flex;
  flex-direction: column;
  scroll-behavior: smooth;
  position: relative;
  z-index: 1;
  max-width: 900px;
  margin: 0 auto;
  width: 100%;
  /* 添加滚动条样式 */
  scrollbar-width: thin;
  scrollbar-color: rgba(156, 39, 176, 0.2) transparent;
}

.messages-container::-webkit-scrollbar {
  width: 6px;
}

.messages-container::-webkit-scrollbar-track {
  background: transparent;
}

.messages-container::-webkit-scrollbar-thumb {
  background: rgba(156, 39, 176, 0.2);
  border-radius: 3px;
}

.messages-container::-webkit-scrollbar-thumb:hover {
  background: rgba(156, 39, 176, 0.4);
}

.welcome-message {
  text-align: center;
  margin: 40px auto;
  color: var(--text-color);
  padding: 24px;
  background: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  max-width: 500px;
  animation: fadeIn 0.6s ease-out;
  border: 1px solid rgba(0, 0, 0, 0.05);
  position: relative;
  overflow: hidden;
  backdrop-filter: blur(10px);
}

.welcome-message::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 4px;
  background: var(--gradient, linear-gradient(to right, #9c27b0, #673ab7));
}

.welcome-message::after {
  content: '';
  position: absolute;
  width: 150px;
  height: 150px;
  background: radial-gradient(circle, rgba(var(--primary-rgb, 156, 39, 176), 0.1) 0%, transparent 70%);
  bottom: -70px;
  right: -70px;
  border-radius: 50%;
}

@keyframes fadeIn {
  from { opacity: 0; transform: translateY(20px); }
  to { opacity: 1; transform: translateY(0); }
}

.welcome-message h3 {
  margin-bottom: 12px;
  color: var(--primary-color, #9c27b0);
  font-weight: 600;
  font-size: 20px;
}

.welcome-message p {
  margin-bottom: 0;
  line-height: 1.6;
  color: #555;
  font-size: 15px;
}

.suggestion-list {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.suggestion-title {
  font-size: 15px;
  color: #555;
  margin-bottom: 6px;
  font-weight: 500;
}

.suggestion-item {
  background-color: #f5f5f5;
  border: 1px solid #e0e0e0;
  border-radius: 12px;
  padding: 10px 18px;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s;
  color: var(--primary-color, #9c27b0);
  width: 100%;
  text-align: left;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
  background: linear-gradient(to right, rgba(255, 255, 255, 0.9), rgba(243, 229, 245, 0.9));
  position: relative;
  z-index: 1;
  overflow: hidden;
}

.suggestion-item::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(120deg, transparent 0%, transparent 50%, rgba(var(--primary-rgb, 156, 39, 176), 0.1) 50%, transparent 100%);
  background-size: 250% 250%;
  z-index: -1;
  transition: all 0.6s ease;
}

.suggestion-item:hover {
  background-color: #e3f2fd;
  border-color: rgba(var(--primary-rgb, 156, 39, 176), 0.2);
  transform: translateY(-2px);
  box-shadow: 0 3px 10px rgba(0, 0, 0, 0.08);
}

.suggestion-item:hover::before {
  background-position: 100% 100%;
}

/* 响应式样式 */
@media (max-width: 767px) {
  .chat-header {
    padding: 12px 16px;
  }
  
  .chat-header h1 {
    font-size: 16px;
  }
  
  .back-btn {
    margin-right: 8px;
    padding: 4px;
  }
  
  .messages-container {
    padding: 16px;
  }
  
  .session-id {
    display: none;
  }
  
  .welcome-message {
    padding: 20px;
    margin: 20px 0;
  }
  
  .suggestion-item {
    padding: 8px 14px;
    font-size: 13px;
  }
  
  .theme-toggle {
    width: 28px;
    height: 28px;
    margin-right: 8px;
  }
  
  .theme-icon {
    font-size: 14px;
  }
  
  .theme-selector {
    right: 10px;
    top: 55px;
    padding: 8px;
  }
}

.message-bubble.system-message {
  background-color: rgba(244, 67, 54, 0.1);
  border: 1px solid rgba(244, 67, 54, 0.3);
  color: #d32f2f;
  font-weight: 500;
  text-align: center;
  max-width: 80%;
  margin: 10px auto;
  padding: 10px 16px;
  border-radius: 8px;
  box-shadow: 0 2px 6px rgba(244, 67, 54, 0.1);
}
</style> 